/**
 * 
 */
package com.effectiv.gooruda.security.rest;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import lombok.extern.slf4j.Slf4j;

import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

import com.stormpath.spring.web.servlet.handler.RestError;

/**
 * @author Dhrubo
 *
 */
@Slf4j
public class RESTAuthenticationFailureHandler implements
		AuthenticationFailureHandler {
	
	private ObjectMapper mapper = new ObjectMapper();

	/* (non-Javadoc)
	 * @see org.springframework.security.web.authentication.AuthenticationFailureHandler#onAuthenticationFailure(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, org.springframework.security.core.AuthenticationException)
	 */
	@Override
	public void onAuthenticationFailure(HttpServletRequest request,
			HttpServletResponse response, AuthenticationException exception)
			throws IOException, ServletException {
		
		log.info("-------- Handling authentication exception - {}" , exception);
		
		RestError error = new RestError(HttpStatus.UNAUTHORIZED, 403, exception.getMessage(), "Authentication failed.", "", exception);
		
		log.info("{}" , mapper.writerWithDefaultPrettyPrinter().writeValueAsString(error));
		response.getWriter().append(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(error));
	}

}
